package com.Web.guardians;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/UploadImage")
@MultipartConfig
public class UploadImageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();

        try {
            Part filePart = request.getPart("file");
            // 获取原始文件名
            String originalFileName = filePart.getSubmittedFileName();
            // 生成新的文件名：时间戳 + 原始扩展名
            String fileName = originalFileName;
            
            // 获取项目根路径
            String projectPath = request.getServletContext().getRealPath("/");
            String uploadPath = projectPath + "img/bg/avater/parent/";  // 添加末尾的斜杠
            
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 保存文件
            filePart.write(uploadPath + fileName);
            
            // 返回相对路径
            String relativePath = "../img/bg/avater/parent/" + fileName;  // 添加末尾的斜杠
            
            result.put("success", true);
            result.put("imagePath", relativePath);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            e.printStackTrace();
        }
        
        out.write(new Gson().toJson(result));
        out.close();
    }
} 